package com.justgame.project.mq.consumer.system;

import com.justgame.mq.client.constant.SystemQueueConstant;
import com.justgame.project.cloud.common.constant.Const;
import com.justgame.project.cloud.common.enums.TimeEnum;
import com.justgame.project.cloud.common.util.MailManager;
import com.justgame.project.cloud.common.util.RabbitHelper;
import com.justgame.project.cloud.common.util.RedisUtils;
import com.justgame.project.service.system.entity.SysUserInfo;
import com.rabbitmq.client.Channel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 用户注册成功
 */
@Slf4j
@Component
@AllArgsConstructor
public class UserRegisterConsumer {
    private final RedisUtils redisUtils;

    @RabbitHandler
    @RabbitListener(queues = SystemQueueConstant.SYSTEM_USER_REGISTER)
    public void userRegister(Channel channel, Message message) throws IOException {
        try {
            SysUserInfo userInfo = RabbitHelper.getBodyEntity(message,SysUserInfo.class);
            /* 发邮件通知该用户已注册成功 */
            MailManager.AfterLogin(userInfo.getEmail(), userInfo.getUserName());
            /* 向redis缓存该用户的数据 */
            redisUtils.set(Const.KEY_REDIS_USER + userInfo.getId(), userInfo, TimeEnum.HOUR.getTime(1) / 1000);

            RabbitHelper.execute(message);
        } catch (Exception e) {
            e.printStackTrace();
            RabbitHelper.receive(message,e);
        } finally {
            // ACK
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
